package org.farm2.wdap.convertor.impl;

import org.farm2.base.db.process.FarmProcessTypeEnum;
import org.farm2.base.db.process.FarmProcessUtils;
import org.farm2.files.domain.ResourceFile;
import org.farm2.files.service.ResourceFileServiceInter;
import org.farm2.tools.files.Farm2FileUtils;
import org.farm2.tools.files.Farm2ProcessState;
import org.farm2.wdap.convertor.filemode.impl.ResourceFileMode;
import org.farm2.wdap.convertor.filemode.impl.TextFileMode;
import org.farm2.wdap.convertor.filemode.inter.FileModel;
import org.farm2.wdap.convertor.inter.FileConvertorInter;
import org.farm2.wdap.convertor.utils.ConvertResult;
import org.farm2.wdap.convertor.utils.ConvertUtils;
import org.farm2.wdap.convertor.utils.ConvertorParam;
import org.farm2.wdap.domain.WdapConvertor;
import org.mozilla.universalchardet.UniversalDetector;
import org.springframework.security.crypto.codec.Utf8;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class TextEncodeConvertor implements FileConvertorInter {

    static {

        ConvertUtils.registImpl((new TextEncodeConvertor()).getClass());
    }

    @Override
    public List<ConvertorParam> getParams() {
        return new ArrayList<>();
    }

    @Override
    public String getTitle() {
        return "编码文本文件";
    }

    @Override
    public String getNote() {
        return "拷贝到模型目录下，同时编码为utf-8";
    }

    @Override
    public ConvertResult runConvert(ResourceFile resourcefile, FileModel filemodel, WdapConvertor convertor, Map<String, ConvertorParam> params, Map<String, Object> flowContext, ResourceFileServiceInter resourceFileServiceImpl) {
        File file = filemodel.getFile(resourcefile, resourceFileServiceImpl);
        FarmProcessUtils.setProcess(resourcefile.getId(), FarmProcessTypeEnum.CONVERT_EXFILE, getTitle() + "...");
        ConvertResult result = new ConvertResult(true);
        TextFileMode textFileMode = new TextFileMode();
        File textdir = textFileMode.getDir(resourcefile, resourceFileServiceImpl);
        File textFile = Paths.get(textdir.toURI()).resolve("text.txt").toFile();
        String text = Farm2FileUtils.readFile(file.getPath());
        String utf8Text = new String(text.getBytes(StandardCharsets.UTF_8));
        Farm2FileUtils.writeToFile(utf8Text, textFile);
        result.addFileModel(textFileMode.getKey());
        return result;
    }


    @Override
    public List<FileModel> getSourceFileModel() {
        return List.of(new ResourceFileMode());
    }

    @Override
    public FileModel getTargetFileModel() {
        return new TextFileMode();
    }

    @Override
    public void valideParams(List<ConvertorParam> params) {
    }
}
